package com.chinaoly.baotou.framework.kafka;

import com.chinaoly.baotou.framework.huawei.LoginUtil;
import com.chinaoly.baotou.framework.huawei.KerberosProperties;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.config.KafkaListenerContainerFactory;
import org.springframework.kafka.core.*;
import org.springframework.kafka.listener.AbstractMessageListenerContainer;

import java.io.IOException;
import java.util.Map;

/**
 * @author xuyh
 */
@Slf4j
@Configuration
@EnableKafka
public class KafkaConfig {

    @Value("${spring.kafka.bootstrap-servers}")
    private String bootstrapServers;

    @Value("${spring.kafka.consumer.enable-auto-commit}")
    private Boolean autoCommit;

    @Value("${spring.kafka.consumer.auto-commit-interval}")
    private Integer autoCommitInterval;

    @Value("${spring.kafka.consumer.group-id}")
    private String groupId;

    @Value("${spring.kafka.consumer.auto-offset-reset}")
    private String autoOffsetReset;

    @Value("${spring.kafka.producer.retries}")
    private Integer retries;

    @Value("${spring.kafka.producer.batch-size}")
    private Integer batchSize;

    @Value("${spring.kafka.producer.buffer-memory}")
    private Integer bufferMemory;


    /**
     * 发送ftp的线程数：默认5
     */
    @Value("${server.thread-ftp:5}")
    private Integer threadFtp;

    /**
     * 入库操作的线程数：默认5
     */
    @Value("${server.thread-db:5}")
    private Integer threadDb;

    @Autowired
    private KerberosProperties kerberosProperties;

    /**
     * 生产者配置信息
     */
    public Map<String, Object> producerConfigs() {
        Map<String, Object> props = Maps.newHashMap();
//        props.put(ProducerConfig.ACKS_CONFIG, "0");
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        props.put(ProducerConfig.RETRIES_CONFIG, retries);
        props.put(ProducerConfig.BATCH_SIZE_CONFIG, batchSize);
        props.put(ProducerConfig.LINGER_MS_CONFIG, 1);
        props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, bufferMemory);
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        if (kerberosProperties.isKafkaEnable()) {
            props.put("kerberos.domain.name", kerberosProperties.getDomainName());
            props.put("security.protocol", kerberosProperties.getSecurityProtocol());
            props.put("sasl.kerberos.service.name", kerberosProperties.getKerberosServiceName());
            props.put("sasl.jaas.config", LoginUtil.jaasContext(kerberosProperties));
            try {
                LoginUtil.setKrb5Config(kerberosProperties.getConf());
                LoginUtil.setJaasFile(kerberosProperties.getPrincipal(), kerberosProperties.getKeytab());
                LoginUtil.setZookeeperServerPrincipal(kerberosProperties.getPrincipal());
            } catch (IOException e) {
                log.error("\n" + e.getMessage());
            }
        }
        return props;
    }

    /**
     * 生产者工厂
     */
    @Bean
    public ProducerFactory<String, String> producerFactory() {
        return new DefaultKafkaProducerFactory<>(producerConfigs());
    }

    /**
     * 生产者模板
     */
    @Bean
    public KafkaTemplate<String, String> kafkaTemplate() {
        return new KafkaTemplate<>(producerFactory());
    }

    /**
     * 消费者配置信息
     */
    public Map<String, Object> consumerConfigs() {
        Map<String, Object> props = Maps.newHashMap();
        props.put(ConsumerConfig.GROUP_ID_CONFIG, groupId);
        props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, autoCommit);
        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, autoOffsetReset);
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        props.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, autoCommitInterval);
        props.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, 40);
        props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, 120000);
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        if (kerberosProperties.isKafkaEnable()) {
            props.put("kerberos.domain.name", kerberosProperties.getDomainName());
            props.put("security.protocol", kerberosProperties.getSecurityProtocol());
            props.put("sasl.kerberos.service.name", kerberosProperties.getKerberosServiceName());
            props.put("sasl.jaas.config", LoginUtil.jaasContext(kerberosProperties));
            try {
                LoginUtil.setKrb5Config(kerberosProperties.getConf());
                LoginUtil.setJaasFile(kerberosProperties.getPrincipal(), kerberosProperties.getKeytab());
                LoginUtil.setZookeeperServerPrincipal(kerberosProperties.getPrincipal());
            } catch (IOException e) {
                log.error("\n" + e.getMessage());
            }
        }
        return props;
    }

    /**
     * 消费者工厂
     */
    public ConsumerFactory<Integer, String> consumerFactory() {
        return new DefaultKafkaConsumerFactory<>(consumerConfigs());
    }
    /**
     * 默认消费者工厂-单线程消费
     */
    @Bean
    public KafkaListenerContainerFactory<?> defaultFactory() {
        ConcurrentKafkaListenerContainerFactory<Integer, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(consumerFactory());
        factory.getContainerProperties().setPollTimeout(3000);
        factory.getContainerProperties().setAckMode(AbstractMessageListenerContainer.AckMode.MANUAL);
        return factory;
    }

}
